<template>
  <div class="material-list-container">
    <el-card>
      <template #header>
        <div class="header-content">
          <span>物资列表</span>
<!--          <el-button type="primary" @click="handleDonate" v-if="userRole === 0">-->
<!--            添加物资-->
<!--          </el-button>-->
        </div>
      </template>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="物资名称">
          <el-input v-model="searchForm.name" placeholder="请输入物资名称" />
        </el-form-item>
        <el-form-item label="物资类别">
          <el-select class="category-select" v-model="searchForm.category" placeholder="请选择类别">
            <el-option
              v-for="item in materialTypes"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <el-col
          v-for="item in materials"
          :key="item.materialId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="material-card" shadow="hover">
            <h3>{{ item.name }}</h3>
            <p class="description">{{ item.description }}</p>
            <div class="meta">
              <span>库存：{{ item.quantity }}</span>
              <span>类别：{{ item.typeName }}</span>
            </div>
            <div class="actions">
              <el-button
                type="primary"
                @click="handleRequest(item)"
                v-if="userRole === 1"
              >
                申请物资
              </el-button>
              <el-button @click="viewDetail(item)">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 24, 32]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 捐赠对话框 -->
    <el-dialog
      v-model="donateDialogVisible"
      title="捐赠物资"
      width="500px"
    >
      <el-form
        ref="donateFormRef"
        :model="donateForm"
        :rules="donateRules"
        label-width="100px"
      >
        <el-form-item label="物资名称" prop="name">
          <el-input v-model="donateForm.name" placeholder="请输入物资名称" />
        </el-form-item>
        <el-form-item label="物资类别" prop="category">
          <el-select v-model="donateForm.category" placeholder="请选择类别">
            <el-option
              v-for="item in materialTypes"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物资描述" prop="description">
          <el-input
            v-model="donateForm.description"
            type="textarea"
            placeholder="请输入物资描述"
          />
        </el-form-item>
        <el-form-item label="捐赠数量" prop="quantity">
          <el-input-number
            v-model="donateForm.quantity"
            :min="1"
            placeholder="请输入捐赠数量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="donateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDonate" :loading="donateLoading">
            确认捐赠
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 申请对话框 -->
    <el-dialog
      v-model="requestDialogVisible"
      title="申请物资"
      width="500px"
    >
      <el-form
        ref="requestFormRef"
        :model="requestForm"
        :rules="requestRules"
        label-width="100px"
      >
        <el-form-item label="申请数量" prop="request_quantity">
          <el-input-number
            v-model="requestForm.request_quantity"
            :min="1"
            :max="selectedMaterial?.quantity"
            placeholder="请输入申请数量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="requestDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRequest" :loading="requestLoading">
            确认申请
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { faker } from '@faker-js/faker'
import {getMaterialCategories, getMaterialList} from "@/api/material.js";

const router = useRouter()
const userRole = ref(Number(localStorage.getItem('userRole') || 0))

// 搜索表单
const searchForm = reactive({
  name: '',
  category: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(100)

// 物资列表
const materials = ref([])

// 物资类型
const materialTypes = ref([])

// 捐赠相关
const donateDialogVisible = ref(false)
const donateFormRef = ref(null)
const donateLoading = ref(false)
const donateForm = reactive({
  name: '',
  category: '',
  description: '',
  quantity: 1
})

const donateRules = {
  name: [{ required: true, message: '请输入物资名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择物资类别', trigger: 'change' }],
  description: [{ required: true, message: '请输入物资描述', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入捐赠数量', trigger: 'blur' }]
}

// 申请相关
const requestDialogVisible = ref(false)
const requestFormRef = ref(null)
const requestLoading = ref(false)
const selectedMaterial = ref(null)
const requestForm = reactive({
  request_quantity: 1
})

const requestRules = {
  request_quantity: [{ required: true, message: '请输入申请数量', trigger: 'blur' }]
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  loadMaterials()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  loadMaterials()
}

// 加载物资列表
const loadMaterials = async () => {
  const data = await getMaterialList({
    page: currentPage.value,
    size: pageSize.value,
    name: searchForm.name,
    typeId: searchForm.category
  })
  materials.value = data.data.records
  total.value = data.data.total
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  loadMaterials()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMaterials()
}

// 捐赠相关方法
const handleDonate = () => {
  donateDialogVisible.value = true
}

const submitDonate = async () => {
  if (!donateFormRef.value) return

  await donateFormRef.value.validate(async (valid) => {
    if (valid) {
      donateLoading.value = true
      try {
        // TODO: 调用捐赠API
        ElMessage.success('捐赠申请已提交')
        donateDialogVisible.value = false
        await loadMaterials()
      } catch (error) {
        console.error('捐赠失败:', error)
      } finally {
        donateLoading.value = false
      }
    }
  })
}

// 申请相关方法
const handleRequest = (material) => {
  selectedMaterial.value = material
  requestForm.request_quantity = 1
  requestDialogVisible.value = true
}

const submitRequest = async () => {
  if (!requestFormRef.value) return

  await requestFormRef.value.validate(async (valid) => {
    if (valid) {
      requestLoading.value = true
      try {
        // TODO: 调用申请API
        ElMessage.success('申请已提交')
        requestDialogVisible.value = false
        loadMaterials()
      } catch (error) {
        console.error('申请失败:', error)
      } finally {
        requestLoading.value = false
      }
    }
  })
}

// 查看详情
const viewDetail = (material) => {
  router.push(`/materials/${material.materialId}`)
}

// 加载物资类型
const loadMaterialTypes = async () => {
  const data = await getMaterialCategories({
    page: 1,
    size: 10000
  })
  materialTypes.value = data.data.records
}

onMounted(() => {
  loadMaterials()
  loadMaterialTypes()
})
</script>

<style scoped>
.material-list-container {
  padding: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.material-card {
  margin-bottom: 20px;
}

.material-card h3 {
  margin: 0 0 10px 0;
}

.description {
  color: #606266;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.meta {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.meta span {
  margin-right: 15px;
}

.actions {
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.category-select {
  width: 150px;
}
</style>
